package cn.six1943.deepchat.module.ai.service.chatsession;

import cn.six1943.deepchat.module.ai.agent.AiConstant;
import cn.six1943.deepchat.module.ai.agent.ChatHandler;
import cn.six1943.deepchat.module.ai.controller.admin.chatsession.vo.ChatRequest;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 *
 */
@AllArgsConstructor
@Service(AiConstant.agent.SERVICE_EXTERNAL)
@Slf4j
public class AgentExternalServiceImpl implements AgentService<ChatRequest> {

    // private final AiProperties props;
    // private final AssistantMapper assistantMapper;

    @Override
    public void answerTheQuestion(ChatRequest request, ChatHandler handler) {
        log.info("开始问答，{}", JSON.toJSONString(request));
        // AssistantEntity botConf = assistantMapper.selectById(request.getAgentId());
        // JSONObject conf = JSON.parseObject(botConf.getAgentConf());
        // StreamingChatModel chatModel = null;
        // switch (botConf.getProvider()) {
        //     case "solu-ai":
        //         chatModel = SoluaiStreamingChatModel.builder()
        //                 .apiKey(conf.getString("sk"))
        //                 .corpId(conf.getString("ak"))
        //                 .appId(conf.getString("uuid"))
        //                 .logRequests(true)
        //                 .logResponses(true)
        //                 .build();
        //         break;
        //     case "dashscope":
        //         chatModel = BailianStreamingChatModel
        //                 .builder()
        //                 .apiKey(conf.getString("api_key"))
        //                 .appId(conf.getString("uuid"))
        //                 .build();
        //         break;
        //     default:
        //         throw new ServiceException("不支持的智能体类型");
        // }
        // Assistant assistant = AiServices.builder(Assistant.class)
        //         .streamingChatModel(chatModel)
        //         .build();
        // List<AgentOutput.DocReference> docReferences = new ArrayList<>();
        // List<AgentOutput.ModelUsage> modelUsages = new ArrayList<>();
        // long start = System.currentTimeMillis();
        // log.info(StrUtil.format("agent::大模型问答开始::{}::{}", request.getSessionId(), start));
        // assistant.answer(request.getQuestion())
        //         .onRetrieved(contents -> {
        //         })
        //         .onPartialResponse(token -> {
        //             log.info(StrUtil.format("agent::大模型问答进行::{}::耗时{}", request.getSessionId(), System.currentTimeMillis() - start));
        //             handler.onChunk(request.getSessionId(), request.getMessageId(), token);
        //         })
        //         .onCompleteResponse(resp -> {
        //             log.info(StrUtil.format("agent::大模型问答结束::{}::{}::耗时{}", request.getSessionId(), System.currentTimeMillis(), System.currentTimeMillis() - start));
        //             TokenUsage usage = resp.tokenUsage();
        //             AiMessageWithDocUsage message = (AiMessageWithDocUsage) resp.aiMessage();
        //             AgentOutput.ModelUsage.ModelUsageBuilder modelUsage = AgentOutput.ModelUsage.builder()
        //                     .modelId(String.valueOf(botConf.getModelId()))
        //                     .inputTokens(usage.inputTokenCount())
        //                     .outputTokens(usage.outputTokenCount())
        //                     .totalTokens(usage.totalTokenCount());
        //             modelUsages.add(modelUsage.build());
        //             if (message.getDocs() != null) {
        //                 for (String doc : message.getDocs()) {
        //                     AgentOutput.DocReference dr = AgentOutput.DocReference.builder()
        //                             .bizId(StrUtil.toString(botConf.getId()))
        //                             // .title(StrUtil.toStringOrNull(tsMetadata.getLong("knowledge_id")))
        //                             // .docId(StrUtil.toStringOrNull(tsMetadata.getLong("item_id")))
        //                             // .indexId(tsMetadata.getString("index"))
        //                             .text(doc)
        //                             .docUrl(doc)
        //                             // .score((Double) metadata.get(ContentMetadata.SCORE))
        //                             .build();
        //                     docReferences.add(dr);
        //                 }
        //             }
        //             AgentOutput output = AgentOutput.builder()
        //                     .models(modelUsages)
        //                     .docReferences(docReferences).build();
        //             handler.onComplete(request.getSessionId(), request.getMessageId(), output);
        //         })
        //         .onError(e -> {
        //             log.info(StringUtil.format("大模型问答报错::{}::{}", request.getSessionId(), System.currentTimeMillis()));
        //             log.error("model api error", e);
        //             handler.onError(request.getSessionId(), request.getMessageId(), e.getMessage());
        //         })
        //         .start();
    }
}
